//
//  ViewController.m
//  SearchBarWithTableView
//
//  Created by My Mac on 2017/6/11.
//  Copyright © 2017年 MyMac. All rights reserved.
//

#import "ViewController.h"
#import "UIImageView+WebCache.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property(nonatomic,strong) NSMutableArray *fixDataArr;
@property(nonatomic,strong) NSMutableArray *displayDataArr;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置tableView和加载数据
    [self setTableViewAttrbitWithLoadData];
}

-(void) setTableViewAttrbitWithLoadData
{
    //初始化数组
    _fixDataArr = [NSMutableArray new];
    _displayDataArr = [NSMutableArray new];
    
    //设置tableView的headerView
    _myTableView.tableHeaderView = [self setTableViewHeaderView];
    
    //加载数据
    //拿到文件路径
    NSString *path = [[NSBundle mainBundle] pathForResource:@"contact.json" ofType:nil];
    //将数据转为NSData类型
    NSData *data = [NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:nil];
    //将data数据转为字典
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    //将数据加到数组中
    for (NSDictionary *tempDict in [dict[@"data"] objectAtIndex:1]) {
        [_fixDataArr addObject:tempDict];
    }
    [_displayDataArr addObjectsFromArray:_fixDataArr];
}

#pragma mark - 将搜索框设为tableView的headerView
-(UIView *)setTableViewHeaderView
{
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, _myTableView.frame.size.width, 40)];
    searchBar.searchBarStyle = UISearchBarStyleMinimal;
    searchBar.placeholder = @"可搜索姓名/手机号";
    searchBar.delegate = self;
    return searchBar;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _displayDataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"myCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    [cell.imageView setImageWithURL:_displayDataArr[indexPath.row][@"avatar_url"] placeholderImage:[UIImage imageNamed:@"tx"]];
    cell.textLabel.text = _displayDataArr[indexPath.row][@"name"];
    cell.detailTextLabel.text = _displayDataArr[indexPath.row][@"phone"];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64;
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if(searchText.length > 0){
        [_displayDataArr removeAllObjects];
        for (NSDictionary *dict in _fixDataArr) {
            //中文姓名
            NSRange nameRange = [dict[@"name"] rangeOfString:searchText options:NSCaseInsensitiveSearch];
            //手机号码
            NSRange phoneRange = [dict[@"phone"] rangeOfString:searchText options:NSCaseInsensitiveSearch];
            //拼音搜索
            //汉字转拼音
            NSArray *pinYinArr = [[self transform:dict[@"name"]] componentsSeparatedByString:@" "];
            NSMutableString *pinYinName = [NSMutableString new];
            for (NSString *str in pinYinArr) {
                [pinYinName appendString:str];
            }
            NSRange pinYinRange = [pinYinName rangeOfString:searchText options:NSCaseInsensitiveSearch];
            if (nameRange.length > 0 || phoneRange.length > 0 || pinYinRange.length > 0) {
                [_displayDataArr addObject:dict];
            }
        }
    } else {
        _displayDataArr = [_fixDataArr mutableCopy];
    }
    [_myTableView reloadData];
}

#pragma mark - 当tableView滚动时，回收键盘
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
    
}

#pragma mark - 汉字转拼音
- (NSString *)transform:(NSString *)chinese
{
    //将NSString装换成NSMutableString
    NSMutableString *pinyin = [chinese mutableCopy];
    //将汉字转换为拼音(带音标)
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL,kCFStringTransformMandarinLatin, NO);
    //去掉拼音的音标
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    //返回最近结果
    return pinyin;
}

@end
